package org.example.jwt.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.jwt.entity.Admin;
import org.example.jwt.utils.JWTUtils;
import org.example.jwt.vo.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Result result = null;
        try{
            DecodedJWT jwt = JWTUtils.verify(token);
            String username = jwt.getClaim("username").asString();
            Integer id = jwt.getClaim("id").asInt();
            Admin admin = new Admin();
            admin.setId(id);
            admin.setUserName(username);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            result = Result.error().setMsg("签名错误");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            result = Result.error().setMsg("token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            result = Result.error().setMsg("算法不匹配");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            result = Result.error().setMsg("失效的token");
        }catch(Exception e){
            e.printStackTrace();
            result = Result.error().setMsg("token无效");
        }
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(json);
        return false;
    }
}
